﻿using Infrastructure.Extensions;
using System.Linq;
using System.Net;
using System.Web;

namespace Infrastructure.Device
{
    /// <summary>
    /// 客户端信息
    /// </summary>
    public static class ClientInfoUtils
    {

        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress()
        {
            string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress))
            {
                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0].Trim();
            }
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && userHostAddress.IsIp())
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 域名转ip
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        public static string HostToIp(string host)
        {
            var list = Dns.GetHostAddresses(host);
            return list.FirstOrDefault()?.ToString() ?? "";
        }
    }
}
